package com.example.ConditionHandlers;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.actionhandlers.IAction;
import com.example.actionhandlers.actions.ChangeSyncOfAccount;
import com.example.actionhandlers.actions.InitApplicationAction;
import com.example.actionhandlers.actions.KillApplicationAction;
import com.example.actionhandlers.actions.MediaPlayAction;
import com.example.priorityobserver.Observable;

public class ActionHandler extends Observable<Map<String, Object>> {
	public static final String NAME = "ACTION";
	private static ActionHandler instance = null;
	List<IAction> supportedActions;

	protected ActionHandler() {
		// Exists only to defeat instantiation.
	}

	public static ActionHandler getInstance() {
		if (instance == null) {
			instance = new ActionHandler();
			instance.init();
		}
		return instance;
	}

	protected void init() {
		addSupportedActions();
	}

	protected void addSupportedActions() {
		supportedActions = new Vector<IAction>();
		IAction initAppAction = new InitApplicationAction();
		supportedActions.add(initAppAction);
		IAction mediaPlayAction = new MediaPlayAction();
		supportedActions.add(mediaPlayAction);
		IAction killApplication = new KillApplicationAction();
		supportedActions.add(killApplication);
		IAction syncAccountAction = new ChangeSyncOfAccount();
		supportedActions.add(syncAccountAction);
	}

	public void performAction(JSONObject conditionOBJECT) {

		try {
			String aaa = conditionOBJECT.getString("action");
			JSONArray jsonArr = new JSONArray(aaa);

			for (int itirator = 0; itirator < jsonArr.length(); itirator++) {
				JSONObject actionObject = (JSONObject) jsonArr.get(itirator);
				for (IAction i : supportedActions)
					if (i.isApplicable(actionObject))
						try {
							i.performAction(actionObject);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return;
		}
		String getConditionName;
		try {
			getConditionName = conditionOBJECT.getString("name");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			return;
		}
		Map<String, Object> eventArgs = new LinkedHashMap<String, Object>();
		eventArgs.put("class", this.getClass().getCanonicalName());
		eventArgs.put("sensorName", ActionHandler.NAME);
		eventArgs.put("eventType", "actionProcess");
		eventArgs.put("condition", getConditionName);
		eventArgs.put("status", "completed");
		notifyObservers(eventArgs);
	}

	public static int getParameterLocation(String parameter) {
		if (parameter.equals("condition"))
			return 1;
		if (parameter.equals("status"))
			return 2;
		return -1;
	}
}